package cn.wolfcode.interceptor;

import cn.wolfcode.domain.Result;
import cn.wolfcode.util.JwtUtils;
import com.alibaba.fastjson.JSON;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取token
        String token = request.getHeader("token");
        try {
            JwtUtils.parseJwt(token);
            return true; // 能解析就放行
        } catch (Exception e) {
            e.printStackTrace();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=utf-8");
            Result notLogin = Result.error("NOT_LOGIN");
            String jsonString = JSON.toJSONString(notLogin);
            response.getWriter().write(jsonString);

            return false; // 无法解析 响应 NOT_LOGIN 信息 不放行
        }
    }
}
